package com.jftone.bh.app.service;

import java.util.List;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.model.SysParam;
import org.apache.log4j.Logger;
import org.jftone.annotation.Autowired;
import org.jftone.annotation.Service;
import org.jftone.annotation.Transactional;
import org.jftone.dao.Dao;
import org.jftone.exception.ComponentException;
import org.jftone.exception.DaoException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;


@Service
public class SysParamService {
	
	private Logger logger = Logger.getLogger(SysParamService.class);
	
	@Autowired
	private Dao dao;
	
	@Transactional
	public void saveSysParam(SysParam param, boolean updateFlag) throws ComponentException{
		String dataType = param.getDataType();
		try{
			if(updateFlag){
//				int paramId = param.getId();
//				if(SysConst.PLATFORM_CONF.equals(dataType)){
//					IData<String, Object> inData = new DataMap<String, Object>();
//					inData.put("id", paramId);
//					SysParam sysParam = dao.get(SysParam.class, inData);
//					if(sysParam == null){
//						return;
//					}
//					inData.clear();
//					inData.put("confType", sysParam.getDataCode());
//					IData<String, Object> setData = new DataMap<String, Object>();
//					setData.put("confType", param.getDataCode());
//					dao.update(ParaConfig.class, setData, inData);
//				}
				dao.update(param);
			}else{
				dao.save(param);
			}
		}catch(DaoException e){
			logger.error("保存系统静态参数信息错误："+e.getMessage(), e);
			throw new ComponentException("保存系统静态参数信息错误："+e.getMessage(), e);
		}
	}
	
	@Transactional
	public int deleteParam(int paramId) throws ComponentException{
		int resultCode = 0;
		try{
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", paramId);
			SysParam param = dao.get(SysParam.class, inData);
			if(param == null){
				return 1;
			}
			if(SysConst.ROOT_CODE.equals(param.getDataType())){
				inData.clear();
				inData.put("dataType", param.getDataCode());
				if(dao.count(SysParam.class, inData)>0){
					return 2;
				}
			}
			dao.delete(param);
		}catch(DaoException e){
			logger.error("删除参数数据错误："+e.getMessage(), e);
			throw new ComponentException("删除参数数据错误："+e.getMessage(), e);
		}
		return resultCode;
	}
	
	public List<SysParam> querySysParam(IData<String, Object> inData) throws ComponentException{
		List<SysParam> paramList = null;
		try{
			paramList = dao.query(SysParam.class, inData);
		}catch(DaoException e){
			logger.error("查询参数数据错误"+e.getMessage(), e);
			throw new ComponentException("查询参数数据错误"+e.getMessage(), e);
		}
		return paramList;
	}
	
	public SysParam getSysParam(IData<String, Object> inData) throws ComponentException{
		SysParam sysParam = null;
		try{
			sysParam = dao.get(SysParam.class, inData);
		}catch(DaoException e){
			logger.error("查询参数数据错误"+e.getMessage(), e);
			throw new ComponentException("查询参数数据错误"+e.getMessage(), e);
		}
		return sysParam;
	}

}
